package com.glacier.framework.boot.autoconfigure.rest;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glacier.framework.boot.rest.response.ObjectToJsonStringMapper;
import com.glacier.framework.boot.rest.response.ResponseAdvice;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * date 2023-12-29 22:32
 *
 * @author glacier
 * @version 1.0
 */
@Configuration
@ConditionalOnClass(value = {ResponseAdvice.class, ObjectToJsonStringMapper.class})
public class RestResponseAdviceAutoConfiguration {

    /**
     * 响应处理
     *
     * @param objectToJsonStringMapper 对象转json
     * @return ResponseAdvice
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(ObjectToJsonStringMapper.class)
    ResponseAdvice responseAdvice(ObjectToJsonStringMapper objectToJsonStringMapper) {
        return new ResponseAdvice(objectToJsonStringMapper);
    }

    @Configuration
    @ConditionalOnClass(value = {ObjectMapper.class})
    static class JacksonAutoConfiguration {

        /**
         * json 序列化
         *
         * @param objectMapper objectMapper
         * @return JsonMapper
         */
        @Bean
        @ConditionalOnMissingBean
        ObjectToJsonStringMapper jacksonObjectToJsonStringMapper(ObjectMapper objectMapper) {
            return (obj) -> {
                String result;
                try {
                    result = objectMapper.writeValueAsString(obj);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                return result;
            };
        }
    }

    @Configuration
    @ConditionalOnClass(value = {JSONObject.class})
    static class fastJsonAutoConfiguration {
        /**
         * json 序列化
         *
         * @return JsonMapper
         */
        @Bean
        @ConditionalOnMissingBean
        ObjectToJsonStringMapper fastJsonObjectToJsonStringMapper() {
            return JSONObject::toJSONString;
        }
    }
}
